import { Component, OnInit } from '@angular/core';
import PerfectScrollbar from 'perfect-scrollbar';
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { LeftSidebarService } from './left-sidebar-service';

declare const $: any;

//Metadata
export interface RouteInfo {
    path: string;
    title: string;
    type: string;
    icontype: string;
    collapse?: string;
    children?: ChildrenItems[];
}

export interface ChildrenItems {
    path: string;
    title: string;
    ab: string;
    type?: string;
}

//Menu Items
export let ROUTES: RouteInfo[] = [{
    path: '/dashboard',
    title: '控制面板',
    type: 'link',
    icontype: 'dashboard'
}, {
    path: '/components',
    title: 'Components',
    type: 'sub',
    icontype: 'apps',
    collapse: 'components',
    children: [
        { path: 'buttons', title: 'Buttons', ab: 'B' },
        { path: 'grid', title: 'Grid System', ab: 'GS' },
        { path: 'panels', title: 'Panels', ab: 'P' },
        { path: 'sweet-alert', title: 'Sweet Alert', ab: 'SA' },
        { path: 'notifications', title: 'Notifications', ab: 'N' },
        { path: 'icons', title: 'Icons', ab: 'I' },
        { path: 'typography', title: 'Typography', ab: 'T' }
    ]
}, {
    path: '/forms',
    title: 'Forms',
    type: 'sub',
    icontype: 'content_paste',
    collapse: 'forms',
    children: [
        { path: 'regular', title: 'Regular Forms', ab: 'RF' },
        { path: 'extended', title: 'Extended Forms', ab: 'EF' },
        { path: 'validation', title: 'Validation Forms', ab: 'VF' },
        { path: 'wizard', title: 'Wizard', ab: 'W' }
    ]
}, {
    path: '/tables',
    title: 'Tables',
    type: 'sub',
    icontype: 'grid_on',
    collapse: 'tables',
    children: [
        { path: 'regular', title: 'Regular Tables', ab: 'RT' },
        { path: 'extended', title: 'Extended Tables', ab: 'ET' },
        { path: 'datatables.net', title: 'Datatables.net', ab: 'DT' }
    ]
}, {
    path: '/maps',
    title: 'Maps',
    type: 'sub',
    icontype: 'place',
    collapse: 'maps',
    children: [
        { path: 'google', title: 'Google Maps', ab: 'GM' },
        { path: 'fullscreen', title: 'Full Screen Map', ab: 'FSM' },
        { path: 'vector', title: 'Vector Map', ab: 'VM' }
    ]
}, {
    path: '/widgets',
    title: 'Widgets',
    type: 'link',
    icontype: 'widgets'

}, {
    path: '/charts',
    title: 'Charts',
    type: 'link',
    icontype: 'timeline'

}, {
    path: '/calendar',
    title: 'Calendar',
    type: 'link',
    icontype: 'date_range'
}, {
    path: '/pages',
    title: 'Pages',
    type: 'sub',
    icontype: 'image',
    collapse: 'pages',
    children: [
        { path: 'pricing', title: 'Pricing', ab: 'P' },
        { path: 'timeline', title: 'Timeline Page', ab: 'TP' },
        { path: 'login', title: 'Login Page', ab: 'LP' },
        { path: 'register', title: 'Register Page', ab: 'RP' },
        { path: 'lock', title: 'Lock Screen Page', ab: 'LSP' },
        { path: 'user', title: 'User Page', ab: 'UP' }
    ]
}
];
@Component({
    selector: 'app-sidebar-cmp',
    templateUrl: 'sidebar.component.html',
})

export class SidebarComponent implements OnInit {
    public menuItems: any[];

    public user: any;
    public jobs: any;
    public currentJobId: string;
    public menuRoleManage = false;
    public menuOrgManage = false;
    public menuProjDeptManage = false;
    public menuAccountManage = false;
    public menuRolePrivilegeManage = false;
    public menuPrivilegeManage = false;
    public menuPositionManage = false;
    public menus: string[];
    public roles: any;
    public org: any;
    public projectDeptComs: any;
    public positionComs: any;
    public rolePrivilegeRoles: any;
    public currentJobName: String;
    constructor(public http: Http, public router: Router, public leftSidebarService: LeftSidebarService) {
        this.leftSidebarService.refresh.subscribe(command => {
            if (command === 'roleManagement') {
                if (this.menus.find(menu => menu === 'manager:role.back.menu') != null) {
                    this.menuRoleManage = true;
                    this.http.get('/user/back/role/trees').map(result => result.json()).subscribe(result => {
                        this.roles = result.trees;
                        localStorage.setItem('role-trees', JSON.stringify(this.roles));
                    }, (error) => {
                        this.roles = null;
                    });
                } else {
                    this.menuRoleManage = false;
                }
            } else if (command === 'orgManagement') {
                if (this.menus.find(menu => menu === 'manager:org.back.menu') != null) {
                    this.menuRoleManage = true;
                    this.http.get('/user/back/org/tree').map(result => result.json()).subscribe(result => {
                        this.org = result.tree;
                        localStorage.setItem('org-tree', JSON.stringify(this.org));
                    }, (error) => {
                        this.org = null;
                    });
                } else {
                    this.menuOrgManage = false;
                }
            }
        });
    }
    showMenus() {
        if (this.menus.find(menu => menu === 'manager:role.back.menu') != null) {
            this.menuRoleManage = true;
            this.http.get('/user/back/role/trees').map(result => result.json()).subscribe(result => {
                this.roles = result.trees;
                localStorage.setItem('role-trees', JSON.stringify(this.roles));
            }, (error) => {
                this.roles = null;
            });
        } else {
            this.menuRoleManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:org.back.menu') != null) {
            this.menuOrgManage = true;
            this.http.get('/user/back/org/tree').map(result => result.json()).subscribe(result => {
                this.org = result.tree;
                localStorage.setItem('org-tree', JSON.stringify(this.org));
            }, (error) => {
                this.org = null;
            });
        } else {
            this.menuOrgManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:project-dept.back.menu') != null) {
            this.menuProjDeptManage = true;
            this.http.get('/user/back/project-dept/trees').map(result => result.json()).subscribe(result => {
                this.projectDeptComs = result.coms;
            }, (error) => {
                this.projectDeptComs = null;
            });
        } else {
            this.menuProjDeptManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:position.back.menu') != null) {
            this.menuPositionManage = true;
            // this.http.get('/user/back/position/trees').map(result => result.json()).subscribe(result => {
            //   this.positionComs = result.coms;
            // }, (error) => {
            //   this.positionComs = null;
            // });
        } else {
            this.menuPositionManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:account.back.menu') != null) {
            this.menuAccountManage = true;
        } else {
            this.menuAccountManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:role-privilege.back.menu') != null) {
            this.menuRolePrivilegeManage = true;
            this.http.get('/user/back/role/trees').map(result => result.json()).subscribe(result => {
                this.rolePrivilegeRoles = result.trees;
            }, (error) => {
                this.rolePrivilegeRoles = null;
            });
        } else {
            this.menuRolePrivilegeManage = false;
        }
        if (this.menus.find(menu => menu === 'manager:privilege.back.menu') != null) {
            this.menuPrivilegeManage = true;
        } else {
            this.menuPrivilegeManage = false;
        }
    }
    changeJob(jobId) {
        this.currentJobId = jobId;
        this.http.get('/user/back/switch-job/' + this.currentJobId).map(rt => rt.json()).subscribe(rt => {
            this.menus = rt.menus;
            this.menuItems = rt.menuLinks;
            ROUTES = rt.menuLinks;
            sessionStorage.setItem('menus', JSON.stringify(this.menus));
            this.showMenus();
            this.leftSidebarService.menusChange.emit('menus');
            for (let i = 0; i < this.jobs.length; i++) {
                if (this.jobs[i].jobId === this.currentJobId) {
                    this.currentJobName = this.jobs[i].jobName;
                }
            }
            this.router.navigate(['/dashboard']);
        });
    }
    showRoleUsers($event, roleId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
    }
    showOrgUsers($event, orgId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
    }
    showProjectDeptUsers($event, projectDeptId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
        alert(projectDeptId);
    }
    manageProjectDepts($event, comId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
        alert('manageProjectDept:' + comId);
    }
    showPositionUsers($event, positionId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
        alert(positionId);
    }
    managePositions($event, comId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
        alert('managePositions:' + comId);
    }
    showRolePrivileges($event, roleId) {
        $('.main-sidebar a').removeAttr('style');
        $($event.target).parent().children('a').css('color', 'white');
        alert(roleId);
    }
    ngOnInit() {
        // this.menuItems = ROUTES.filter(menuItem => menuItem);
        this.http.get('/user/back/menu-links').map(rt => rt.json()).subscribe(rt => {
            this.menuItems = rt.menuLinks;
            ROUTES = rt.menuLinks;
        });
        this.currentJobName = '正在获取用户职务...';
        this.user = JSON.parse(sessionStorage.getItem('user'));
        this.http.get('/user/back/jobs').map(rt => rt.json()).subscribe(rt => {
            this.jobs = rt.jobs;
            this.currentJobId = rt.currentJobId;
            for (let i = 0; i < this.jobs.length; i++) {
                if (this.jobs[i].jobId === this.currentJobId) {
                    this.currentJobName = this.jobs[i].jobName;
                }
            }
        });
        this.http.get('/user/back/menu-codes').map(result => result.json()).subscribe(result => {
            this.menus = result.menus;
            sessionStorage.setItem('menus', JSON.stringify(this.menus));
            this.leftSidebarService.menusChange.emit('menus');
            this.showMenus();
        });
    }
    isMobileMenu() {
        if ($(window).width() > 991) {
            return false;
        }
        return true;
    };
    updatePS(): void {
        if (window.matchMedia(`(min-width: 960px)`).matches && !this.isMac()) {
            const elemSidebar = <HTMLElement>document.querySelector('.sidebar .sidebar-wrapper');
            let ps = new PerfectScrollbar(elemSidebar, { wheelSpeed: 2, suppressScrollX: true });
        }
    }
    isMac(): boolean {
        let bool = false;
        if (navigator.platform.toUpperCase().indexOf('MAC') >= 0 || navigator.platform.toUpperCase().indexOf('IPAD') >= 0) {
            bool = true;
        }
        return bool;
    }
}
